// @Author: cyl
// @File: run_stop.go
// @Time: 2023/07/01 21:12:51
package main

import (
	"context"
	"log"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"

	"github.com/gin-gonic/gin"
)

func RunStopGin() {
	r := gin.Default()

	srv := &http.Server{
		Addr:    ":8080",
		Handler: r,
	}

	// 启动协程保证程序优雅的启动和退出
	go func() {
		log.Printf("web service running in %s\n", srv.Addr)
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalln(err)
		}
	}()

	quit := make(chan os.Signal)
	signal.Notify(quit, syscall.SIGILL, syscall.SIGTERM)
	<-quit
	log.Println("shutting down project web server...")

	ctx, channel := context.WithTimeout(context.Background(), 2*time.Second)
	defer channel()
	if err := srv.Shutdown(ctx); err != nil {
		log.Fatalln("web server shutting down, caused by:", err)
	}
	select {
	case <-ctx.Done():
		log.Panicln("wait timeout...")
	}
	log.Println("web server stop success...")
}
